# -*- coding: utf-8 -*-
# frontend/components/chat_interface.py
"""
聊天界面组件
"""

import streamlit as st
import asyncio
from typing import Dict, List, Any
from backend.services.chat_service import ChatService
from frontend.utils.ui_helpers import display_model_badge, format_timestamp
import logging

logger = logging.getLogger(__name__)

class ChatInterface:
    """聊天界面类"""
    
    def __init__(self):
        self.chat_service = None
        self.initialize_chat_service()
    
    def initialize_chat_service(self):
        """初始化聊天服务"""
        api_keys = st.session_state.get("api_keys", {})
        if api_keys:
            try:
                self.chat_service = ChatService(api_keys)
                logger.info("聊天服务初始化成功")
            except Exception as e:
                logger.error(f"聊天服务初始化失败: {e}")
                st.error(f"聊天服务初始化失败: {str(e)}")
    
    def render_chat_history(self):
        """渲染聊天历史"""
        chat_history = st.session_state.get("chat_history", [])
        
        if not chat_history:
            st.markdown("""
            <div style="text-align: center; padding: 3rem; color: #666;">
                <h3>👋 欢迎使用智能AI群聊系统！</h3>
                <p>选择您喜欢的AI模型，开始精彩的对话吧~</p>
                <p>💡 小贴士：可以同时选择多个AI模型，获得不同角度的回答</p>
            </div>
            """, unsafe_allow_html=True)
            return
        
        # 渲染消息
        for message in chat_history:
            self.render_message(message)
    
    def render_message(self, message: Dict[str, Any]):
        """渲染单条消息"""
        role = message["role"]
        content = message["content"]
        timestamp = message.get("timestamp", "")
        
        if role == "user":
            st.markdown(f"""
            <div class="chat-message user-message">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                    <strong>👤 您</strong>
                    <small style="color: #666;">{format_timestamp(timestamp)}</small>
                </div>
                <div>{content}</div>
            </div>
            """, unsafe_allow_html=True)
            
        elif role == "assistant":
            models = message.get("models", ["AI"])
            model_badges = " ".join([display_model_badge(model) for model in models])
            
            st.markdown(f"""
            <div class="chat-message assistant-message">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                    <div>
                        <strong>🤖 AI助手</strong>
                        <div style="margin-top: 0.25rem;">{model_badges}</div>
                    </div>
                    <small style="color: #666;">{format_timestamp(timestamp)}</small>
                </div>
                <div>{content}</div>
            </div>
            """, unsafe_allow_html=True)
            
            # 显示个别响应（如果有多个模型）
            individual_responses = message.get("individual_responses", {})
            if len(individual_responses) > 1:
                with st.expander("查看各AI的独立回答", expanded=False):
                    for model, response in individual_responses.items():
                        st.markdown(f"""
                        **{display_model_badge(model)}**
                        
                        {response}
                        
                        ---
                        """, unsafe_allow_html=True)
    
    def render_input_area(self):
        """渲染输入区域"""
        st.markdown("### 💭 发送消息")
        
        # 检查是否有可用的API密钥
        if not st.session_state.get("api_keys"):
            st.warning("⚠️ 请先在系统设置中配置API密钥")
            return
        
        # 检查是否选择了模型
        if not st.session_state.get("selected_models"):
            st.warning("⚠️ 请在侧边栏选择至少一个AI模型")
            return
        
        # 消息输入
        col1, col2 = st.columns([4, 1])
        
        with col1:
            user_input = st.text_area(
                "输入您的问题",
                height=100,
                placeholder="请输入您想要询问的问题...",
                label_visibility="collapsed"
            )
        
        with col2:
            send_button = st.button("🚀 发送", use_container_width=True, type="primary")
            
            st.markdown("<br>", unsafe_allow_html=True)
            
            # 快捷操作按钮
            if st.button("📋 示例问题", use_container_width=True):
                st.session_state.show_examples = not st.session_state.get("show_examples", False)
        
        # 显示示例问题
        if st.session_state.get("show_examples", False):
            st.markdown("**💡 示例问题:**")
            examples = [
                "解释一下量子计算的基本原理",
                "帮我写一个Python爬虫脚本",
                "如何提高团队协作效率？",
                "分析一下当前AI技术的发展趋势"
            ]
            
            for example in examples:
                if st.button(f"'{example}'", key=f"example_{example}"):
                    st.session_state.example_selected = example
                    st.rerun()
        
        # 处理用户输入
        message_to_send = user_input
        if st.session_state.get("example_selected"):
            message_to_send = st.session_state.example_selected
            st.session_state.example_selected = None
        
        if send_button and message_to_send.strip():
            self.handle_user_message(message_to_send.strip())
    
    def handle_user_message(self, message: str):
        """处理用户消息"""
        if not self.chat_service:
            st.error("聊天服务未初始化，请检查API配置")
            return
        
        # 添加用户消息到历史
        user_message = {
            "role": "user",
            "content": message,
            "timestamp": str(asyncio.get_event_loop().time())
        }
        
        if "chat_history" not in st.session_state:
            st.session_state.chat_history = []
        
        st.session_state.chat_history.append(user_message)
        
        # 显示加载状态
        with st.spinner("AI们正在思考中..."):
            try:
                # 获取AI响应
                response = asyncio.run(self._get_ai_response(message))
                
                if response:
                    # 添加AI响应到历史
                    ai_message = {
                        "role": "assistant",
                        "content": response["response"],
                        "models": response["selected_models"],
                        "individual_responses": response["individual_responses"],
                        "timestamp": str(asyncio.get_event_loop().time()),
                        "metadata": response.get("metadata", {})
                    }
                    
                    st.session_state.chat_history.append(ai_message)
                    
                    # 显示成功提示
                    processing_time = response.get("processing_time", 0)
                    st.success(f"✅ 响应完成！用时 {processing_time:.2f} 秒")
                else:
                    st.error("获取AI响应失败")
                    
            except Exception as e:
                logger.error(f"处理消息失败: {e}")
                st.error(f"处理消息时出现错误: {str(e)}")
        
        # 重新运行以显示新消息
        st.rerun()
    
    async def _get_ai_response(self, message: str) -> Dict[str, Any]:
        """获取AI响应"""
        try:
            conversation_id = st.session_state.get("conversation_id")
            if not conversation_id:
                conversation_id = await self.chat_service.create_conversation()
                st.session_state.conversation_id = conversation_id
            
            selected_models = st.session_state.get("selected_models", ["gpt-4"])
            
            response = await self.chat_service.send_message(
                message=message,
                conversation_id=conversation_id,
                selected_models=selected_models,
                stream=st.session_state.get("stream_response", False)
            )
            
            return response
            
        except Exception as e:
            logger.error(f"获取AI响应失败: {e}")
            raise
